package com.zzb.codegenerator.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by zhangzhenbin on 17-8-24.
 */
public class GetJdbcUrlUtil {
    //DriverName
    public static String getDriverName(String connectionUrl) {
        if (connectionUrl.contains("jtds")) {
            return "net.sourceforge.jtds.jdbc.Driver";
        }
        if (connectionUrl.contains("sqlserver")) {
            return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        }
        if (connectionUrl.contains("mysql")) {
            return "com.mysql.jdbc.Driver";
        }
        if (connectionUrl.contains("postgresql")) {
            return "org.postgresql.Driver";
        }
        if (connectionUrl.contains("jdbc:hive2")){
            return "org.apache.hive.jdbc.HiveDriver";
        }
        return null;
    }

    //获取jdbcUrl链接
    public static String getJdbcUrl(String jdbcDriver, String serverHost, String serverPort, String dbName, String schema) {
        StringBuilder sb = null;
        if (jdbcDriver.equals("org.postgresql.Driver")) {
            sb = new StringBuilder("jdbc:postgresql://")
                    .append(serverHost)
                    .append(":")
                    .append(serverPort)
                    .append("/")
                    .append(dbName);
        } else if (jdbcDriver.equals("net.sourceforge.jtds.jdbc.Driver")) {
            sb = new StringBuilder("jdbc:jtds:sqlserver://")
                    .append(serverHost)
                    .append(StringUtils.isBlank(serverPort) ? "" : (":" + serverPort))
                    .append("/")
                    .append(dbName);
        } else if (jdbcDriver.equals("org.apache.hive.jdbc.HiveDriver")) {
            sb = new StringBuilder("jdbc:hive2://")
                    .append(serverHost)
                    .append(StringUtils.isBlank(serverPort) ? "" : (":" + serverPort))
                    .append("/")
                    .append(dbName);
        } else {
            sb = new StringBuilder("jdbc:mysql://")
                    .append(serverHost)
                    .append(":")
                    .append(serverPort)
                    .append("/")
                    .append(schema)
                    .append("?useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull");
        }
        return sb.toString();
    }
}
